package com.oa.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oa.mapper.admin.AdminMapper;
import com.oa.mapper.user.DeptMapper;
import com.oa.mapper.user.EduMapper;
import com.oa.mapper.user.PositionMapper;
import com.oa.mapper.user.UserMapper;
import com.oa.pojo.*;
import com.oa.service.admin.AdminService;
import com.oa.service.user.FileUploadService;
import com.oa.vo.EmpVo;
import com.oa.vo.FileUploadVo;
import com.oa.vo.PageResult;
import com.qiniu.common.QiniuException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 一拳超人
 * @Date: 2021/10/15 19:03
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private EduMapper eduMapper;

    @Autowired
    private FileUploadService fileUploadService;

    @Override
    public Admin loginAuth(Admin admin) {
        admin.setAdminPassword(DigestUtils.md5DigestAsHex(admin.getAdminPassword().getBytes(StandardCharsets.UTF_8)));
        return adminMapper.selectOne(new QueryWrapper<>(admin));
    }

    /**
     * 后台管理页面员工信息查询
     *
     * @param page 分页对象
     * @return 查询到的员工信息列表
     */
    @Override
    public Page<EmpVo> selectUserInfo(Page<EmpVo> page, PageResult pageResult) {
        return userMapper.selectAllEmpList(page, pageResult.getQuery());
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Integer updateEmpStatus(Emp emp) {
        if (emp.getEmpStatus()) {
            emp.setResignDate(null);
        } else {
            emp.setResignDate(new java.sql.Date(new java.util.Date().getTime()));
        }
        int i = userMapper.updateById(emp);
        return i != 0 ? 200 : 201;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Integer deleteEmp(Integer id) {
        int i = 201;
        Emp emp = userMapper.selectById(id);
        if (emp != null) {
            List<Department> departments = deptMapper.selectList(new QueryWrapper<Department>()
                    .eq("manager_id", emp.getEmpId()));
            if (departments.size() != 0) {
                return i;
            } else {
                userMapper.deleteById(id);
                i = 0;
            }
        }
        return i;
    }

    @Override
    public String generateEmpId() {
        QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("emp_id").last("limit 1");
        Emp emp = userMapper.selectOne(queryWrapper);
        Long empId = Long.parseLong(emp.getEmpId()) + 1;
        return String.valueOf(empId);
    }

    @Override
    public List<Position> getPositionInfo(Integer depId) {
        return positionMapper.selectList(new QueryWrapper<Position>().eq("dep_id", depId));
    }

    @Override
    public List<Edu> getEduInfo() {
        return eduMapper.selectList(null);
    }

    @Override
    public Integer addNewEmp(Emp emp) {
        String password = DigestUtils.md5DigestAsHex(emp.getEmpPassword().getBytes());
        int i = userMapper.insert(emp.setEmpPassword(password));
        return i != 0 ? 200 : 201;
    }

    @Override
    public Integer updateEmpInfo(Emp emp) {
        int i = userMapper.updateById(emp);
        return i != 0 ? 200 : 201;
    }

    @Override
    public Emp getEmpInfo(Integer id) {
        Emp emp = userMapper.selectById(id);
        emp.setPositionName(positionMapper.selectOne(new QueryWrapper<Position>()
                .eq("position_id", emp.getPositionId())).getPositionName())
                .setDepName(deptMapper.selectOne(new QueryWrapper<Department>()
                        .eq("dep_id", emp.getDepId())).getDepName());
        return emp;
    }

    @Override
    public FileUploadVo uploadEmpPhoto(InputStream inputStream) throws QiniuException {
        return fileUploadService.uploadFile(inputStream);
    }

    @Override
    public Integer deleteEmpPhoto(String key) throws QiniuException {
        return fileUploadService.deleteUploadFile(key);
    }

    /**
     * 获取部门信息
     *
     * @param level 部门等级
     * @return 部门信息
     */
    @Override
    public List<Department> getDepartmentInfo(Integer level) {
        Map<Integer, List<Department>> map = getMap();
        if (level == 1) {
            return map.get(0);
        }
        return getOneList(map);
    }

    private Map<Integer, List<Department>> getMap() {
        Map<Integer, List<Department>> map = new HashMap<>();
        List<Department> departments = deptMapper.selectList(null);
        for (Department department : departments) {
            department.setDepManager(userMapper.selectOne(new QueryWrapper<Emp>()
                    .eq("emp_id", department.getManagerId())).getEmpName());
            Integer parentId = department.getParentId();
            if (map.containsKey(parentId)) {
                map.get(parentId).add(department);
            } else {
                ArrayList<Department> childrenLists = new ArrayList<>();
                childrenLists.add(department);
                map.put(parentId, childrenLists);
            }
        }
        return map;
    }

    private List<Department> getOneList(Map<Integer, List<Department>> map) {
        List<Department> oneLists = map.get(0);
        for (Department oneList : oneLists) {
            List<Department> twoLists = map.get(oneList.getDepId());
            oneList.setChildren(twoLists);
        }
        return oneLists;
    }
}
